import {usePages} from '@/hooks/usePages'
import {urlParse} from '@/utils/utils'
import {fetchLatestMeetingInfo, fetchMeetingInfoById} from '@/api/meeting'
import to from 'await-to-js'
import {tip} from '@/utils/uni-api-wrap/toast'
import {getLaunchOptionsSync} from '@/utils/uni-api-wrap/page'
import {onLoad} from '@dcloudio/uni-app'

export const useMeeting = () => {
  const meetingDetail = ref(null)

  const getQueryMeetingId = (query = {}) => {
    let id = ''
    if (query.id) {
      id = query.id
    } else if (query.scene) {
      const sceneQuery = urlParse(`?${decodeURIComponent(query.scene)}`)
      if (sceneQuery.id) {
        id = sceneQuery.id
      }
    }
    return id
  }

  const fetchMeetingInfo = async id => {
    const [err, result] = await to(id ? fetchMeetingInfoById(id) : fetchLatestMeetingInfo())
    if (err) return
    if (result.code !== 0) return tip(result.msg || '找不到议会信息')
    meetingDetail.value = result.data
  }

  onLoad((query) => {
    const queryMeetingId = getQueryMeetingId(query)
    fetchMeetingInfo(queryMeetingId)
  })

  const reload = () => {
    fetchMeetingInfo(getQueryMeetingId())
  }

  return { meetingDetail, reload }
}
